<script setup>
import topNav from "../../components/topNav.vue";
import {
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  computed,
  nextTick,
} from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
// import { appStockQuery } from "@/services/goods";
import { appStockQuery } from "@/services/transfer.js";
import { operation } from "@/utils/num.js";
import { appProductQuery } from "@/services/goods";

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const code = ref("");
const payNum = ref(0);

onLoad((option) => {
  code.value = option.code ? option.code : "";
  form.value.keyword = option.code ? option.code : "";
  if (uni.getStorageSync("goodsSel")) {
    console.log("goodsSel", uni.getStorageSync("goodsSel"));
    selectNumList.value = JSON.parse(uni.getStorageSync("goodsSel"));
    selectNumList.value.forEach((item) => {
      goodsNum.value = goodsNum.value + Number(item.transferNum);
      // payPrice.value = operation(
      //   payPrice.value,
      //   operation(item.transferNum, item.taxPrice, 2, "multiply"),
      //   2,
      //   "add"
      // );
    });
  }

  // if (uni.getStorageSync("shopselect")) {
  //   selectShopObj.value = JSON.parse(uni.getStorageSync("shopselect"));
  // }
});

const ishowcamera = ref(false);
const scanFun = () => {
  selectNumList.value.forEach((item, index) => {
    if (item.transferNum <= 0) {
      selectNumList.value.splice(index, 1);
    }
  });
  console.log("扫码");
  uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=selfStore" });
  // #endif
  // 允许从相机和相册扫码
  // #ifdef APP-PLUS

  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  code.value = res.result;
                  form.value.keyword = res.result;
                  getappStockQuery(1);
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      code.value = res.result;
      form.value.keyword = res.result;
      getappStockQuery(1);
    },
  });
  // #endif
};

const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getappStockQuery(1);
};
const isShowBtn = ref(true);
const searchFun = (val) => {
  console.log("取2消");
  form.value.keyword = val;
  loading.value = "";
  console.log(form.value.name);
  getappStockQuery(1);
};
const focusFun = () => {
  isShowBtn.value = false;
};
const blurFun = () => {
  isShowBtn.value = true;
};

onReachBottom(() => {
  console.log("触底了");
  getappStockQuery();
});
onMounted(() => {
  getappStockQuery();
});

//获取商品
const form = ref({
  categoryId: "",
  pageIndex: 1,
  pageSize: 20,
  barCode: "",
  code: "",
  name: "",
  skuCode: "",
  categoryId: "",
  available: "",
  keyword: "",
});

const goodsNum = ref(0);
const payPrice = ref(0);
const itemObj = ref({});
const priceValue = ref(0);
const selectitem = ref(0);

const productData = ref([]);

const loading = ref("");
const getappStockQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await appProductQuery(form.value);
    if (res.code == 200) {
      res.data.datas.forEach((element) => {
        let ifHave = false;
        selectNumList.value.forEach((item) => {
          if (element.id == item.id) {
            ifHave = true;
            element.transferNum = item.transferNum;
            element.newsalePrice = item.newsalePrice;
          }
        });
        if (!ifHave) {
          element.transferNum = 0;
        }
      });
      productData.value = productData.value.concat(res.data.datas);
      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};
function getNum() {
  let num = 0;
  selectNumList.value.forEach((item) => {
    num += Number(item.transferNum);
    console.log(item.transferNum, "num");
  });
  goodsNum.value = num;
}
const selectNumList = ref([]);
const selectItem = ref({});
const showMode = ref(false);
const showIndex = ref(0);
const showTwoIndex = ref(0);

const valChange = (item, index, e) => {
  selectItem.value = item;
  showIndex.value = index;

  if (e.value > item.stockNum) {
    showMode.value = true;
  }

  if (selectNumList.value <= 0) {
    selectNumList.value.push(item);
    getNum();
    return;
  }
  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == item.id) {
      showTwoIndex.value = index1;
      selectNumList.value[index1] = item;
      isnew = false;
    }
  });
  if (isnew) {
    showTwoIndex.value = selectNumList.value.length;
    selectNumList.value.push(item);
  }
  console.log(selectNumList.value, "sadas");
  setTimeout(() => {
    selectNumList.value.forEach((item, index) => {
      if (item.transferNum <= 0) {
        selectNumList.value.splice(index, 1);
      }
    });
    getNum();
  }, 100);
};

const blurChange = (item, index, e) => {
  if (e.value == "") {
    item.transferNum = 0;
  }
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/goods/goods_add/index?id=" + item.id });
};

const cancelFun = () => {
  showMode.value = false;
  productData.value[showIndex.value].transferNum =
    productData.value[showIndex.value].stockNum;

  selectNumList.value[showTwoIndex.value].transferNum =
    selectNumList.value[showTwoIndex.value].stockNum;

  getNum();
};
const confirmFun = () => {
  showMode.value = false;
};
//改价列表
const goRecord = () => {
  // selectNumList.value.forEach((item, index) => {
  //   if (item.transferNum <= 0) {
  //     selectNumList.value.splice(index, 1);
  //   }
  // });
  if (selectNumList.value.length <= 0) {
    uni.showToast({
      title: "请先选择商品",
      icon: "none",
    });
    return;
  }

  uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));

  uni.navigateTo({
    url: "/pages/self_store/goods_swith/index",
  });
};

const keyWord = ref(null);

//金额键盘
const inp = (e) => {
  console.log("e", e);
  isPrice.value = true;
};

const hide = () => {
  if (num.value > 0) {
    // numblur();
  } else {
    jsnum.value = 0;
  }
  // isinputto.value = false;
  // isshowput.value = true;
};
const selectNumIndex = ref(-1);
const isPrice = ref(false);
const del = (e) => {
  if (e == 0) {
    selectNumIndex.value = selectNumIndex.value - 1;
  } else if (e == 1) {
    selectNumIndex.value = selectNumIndex.value + 1;
  }
};
const keyWordItem = (index) => {
  isPrice.value = true;
  selectNumIndex.value = index;
};
const confirm = async () => {
  // getcomputeBrokerage(Number(num.value));

  // goodsNum.value = goodsNum.value + 1;
  productData.value[selectitem.value].transferNum = priceValue.value;
  productData.value[selectitem.value].newsalePrice = String(
    itemObj.value.salePrice
  );
  // productData.value[selectitem.value].salePrice=priceValue.value
  nextTick(() => {
    keyWord.value.close();
    // isshowput.value = true;
  });

  let isnew = true;
  selectNumList.value.forEach((item1, index1) => {
    if (item1.id == itemObj.value.id) {
      isnew = false;
      selectNumList.value[index1] = itemObj.value;
    }
  });
  if (isnew) {
    selectNumList.value.push(itemObj.value);
  }
  uni.setStorageSync("goodsSel", JSON.stringify(selectNumList.value));
  getNum();

  // getappStockQuery(1);
  show.value = false;
};
const onClickMinus = (item, index) => {
  itemObj.value = item;
  selectitem.value = index;
  priceValue.value = String(item.transferNum);
  keyWord.value.open();
};
//无网状态
const connected = () => {
  getappStockQuery();
};
</script>

<template>
  <jia-PayKeyboard
    :confirmStyle="{ backgroundColor: '#1679FB' }"
    class="keyWord-index"
    :overlayClose="true"
    ref="keyWord"
    v-model="priceValue"
    :showPoint="false"
    :sclectItem="selectNumIndex"
    @input="inp"
    @del="del"
    @confirm="confirm"
    @hide="hide"
  >
    <view class="PayKeyboard-k">
      <view class="icon-top">
        <up-icon
          @click="closePay"
          name="close"
          color="#86909C"
          size="20"
        ></up-icon
      ></view>
      <view class="PayKeyboard-k-title-k">
        <view class="images">
          <image
            :src="
              itemObj.image ||
              'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
            "
            mode="scaleToFill"
          />
        </view>
        <view>
          <view class="PayKeyboard-k-title">{{ itemObj.name }}</view>
          <view class="PayKeyboard-k-des">{{ itemObj.barCode }}</view>
        </view>
      </view>

      <view class="link-to"></view>

      <view class="PayKeyboard-k-num">
        <view class="PayKeyboard-k-num-title">价格</view>
        <view class="PayKeyboard-k-num-input">
          <up-form labelPosition="left" ref="form1" labelWidth="0">
            <up-form-item label=" " borderBottom ref="item1">
              <up-input
                @focus="isPrice = false"
                class="input-num"
                placeholder="请输入价格"
                border="none"
                type="number"
                v-model="itemObj.salePrice"
                :customStyle="{
                  fontSize: '52rpx',
                }"
              ></up-input>
              <template #right>
                <text>元</text>
              </template>
            </up-form-item>
          </up-form>
        </view>
      </view>

      <view class="PayKeyboard-k-num">
        <view class="PayKeyboard-k-num-title">数量</view>
        <view class="PayKeyboard-k-num-input">
          <up-form labelPosition="left" ref="form1" labelWidth="0">
            <up-form-item
              label=" "
              borderBottom
              ref="item1"
              @click="keyWordItem(-1)"
            >
              <view class="PayKeyboard-k-num-input-text">
                <view
                  class="num-view"
                  v-for="(item, index) in priceValue"
                  :key="index"
                  @click.stop="keyWordItem(index)"
                  ><view
                    :class="isPrice ? 'input_lin' : ''"
                    v-if="selectNumIndex == index"
                  ></view
                  >{{ item }}</view
                >
                <view
                  :class="isPrice ? 'input_lin' : ''"
                  v-if="selectNumIndex == -1"
                ></view>
              </view>
              <template #right>
                <text>{{ itemObj.unit }}</text>
              </template>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </view>
  </jia-PayKeyboard>

  <topNav
    title="自采入库商品搜索"
    @save="saveFun"
    @scan="scanFun"
    rType="cancel"
    @search="searchFun"
    @blurfun="blurFun"
    @focusfun="focusFun"
    :IsSearch="true"
    :code="code"
  ></topNav>
  <view class="goods_form">
    <view
      class="scroll-Y-item"
      v-for="(item, index) in productData"
      :key="index"
      @click="onClickMinus(item, index)"
    >
      <view class="scroll-item-left">
        <image
          :src="
            item.image ||
            'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
          "
          mode="scaleToFill"
        />
      </view>
      <view class="scroll-item-right">
        <view class="goods-item-title"> {{ item.name }} </view>
        <!-- <view class="goods-item-spec">
          条形码: {{ item.barCode ? item.barCode : "--" }}
        </view> -->
        <view class="goods-item-spec" v-if="!item.dhCode">
          商品码:{{ item.barCode ? item.barCode : "" }}</view
        >
        <view class="goods-item-spec" v-if="item.dhCode">
          称码:{{ item.dhCode ? item.dhCode : "" }}</view
        >
        <view class="goods-item-price">
          ¥{{ item.salePrice ? item.salePrice : 0.0 }}
          {{ item.unit ? "/" + item.unit : "" }}
          <text class="goods-item-spec">库存:</text>
          {{ item.stockNum || 0 }}
        </view>
      </view>
      <view class="goods-item-num">
        <up-icon
          name="plus-circle-fill"
          color="#1679fb"
          size="60rpx"
          v-if="item.transferNum <= 0"
        ></up-icon>
        <view v-if="item.transferNum > 0" class="selectindex"
          >入价¥{{ item.newsalePrice }}</view
        >
        <view v-if="item.transferNum > 0" class="selectindex"
          >数量¥{{ item.transferNum }}</view
        >
      </view>
    </view>
  </view>
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无商品 </view>
    </view>
  </view>
  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>

  <view style="height: 100rpx; width: 100%"></view>

  <view class="goods_bt" v-if="isShowBtn">
    <view class="goods_bt_to">
      <text>共{{ selectNumList.length }}款,{{ goodsNum }}件</text>
      <van-button class="val-button" type="primary" @click="goRecord"
        >确认</van-button
      >
    </view>
  </view>

  <up-modal
    :show="showMode"
    :title="
      selectItem.name +
      ', 库存超出' +
      (selectItem.stockNum - selectItem.transferNum)
    "
    width="500rpx"
    :content="''"
    @cancel="cancelFun"
    @confirm="confirmFun"
    confirmText="仍然调货"
    cancelText="取消"
    :showCancelButton="true"
  ></up-modal>

  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
